import { menulist } from '../api/system'
import { info } from '../api/role'
import store from '../store'
let permission = {
  menulist: [],
  roleMenuList: [],
  path: '',
  routes: [],
  init(path, routes) {
    this.path = path;
    this.routes = routes;
    var _this = this;
    return new Promise(function (resolve, reject) {
      if (path == '/404') {
        resolve()
        return
      }
      //判断是否登录
      if (!store.getters.get_token) {
        console.log('未登录');
        let code = _this.exit404() ? 404 : 110;
        resolve({ code: code })
        return
      }
      //判断菜单是否加载
      if (store.getters.get_menu) {
        console.log('未加载');
        let code = _this.exit404() ? 404 : -1;
        resolve({ code: code })
        return
      }

      //获取菜单接口
      menulist({}).then(d => {

        if (d.code == 200) {

          _this.menulist = d.data;
          // console.log(1111111, d.data);
          _this.getPromise().then(function (d) {
            if (d) {
              let code = _this.exit404(d) ? 404 : 1;
              resolve({ code: code, data: d })
            } else {
              let code = _this.exit404() ? 404 : 1;
              resolve({ code: code })
            }
          });
        } else {
          this.$messges.error(d.msg);
        }
      }).catch((e) => {
        console.log(e);
        resolve()
      })
    });
  },
  exit404(d) {
    // console.log(d);
    if (d) {
      this.routes = d.concat(this.routes);
    }
    var n404 = true;
    if (this.routes.findIndex(e => e.path == this.path) >= 0) {
      n404 = false;
    }
    if (n404) {
      this.routes.forEach(e => {
        if (e.children && e.children.findIndex(c => c.path == this.path) >= 0) {
          n404 = false;
        }
      })
    }
    return n404;
  },
  getPromise() {
    var _this = this;
    return new Promise(function (resolve, reject) {
      //获取角色菜单
      // let roleList = store.getters.get_user.roleList;
      // console.log(111111, roleList);
      // console.log('菜单列表', roleList);
      var token = JSON.parse(window.sessionStorage.getItem("token"));
      var roleId = token.roleId;

      if (roleId != undefined && roleId != null) {
        info({ roleId: roleId }).then(d => {
          // console.log('info', d);
          if (d.code == 200) {
            // console.log(22222, d.data);
            //菜单拼装
            _this.roleMenuList = _this.pinPromise(d.data);
            // console.log(_this.roleMenuList, "rolemenulist")
            //缓存菜单
            store.dispatch('set_menu', _this.roleMenuList).then(() => {
              resolve(_this.roleMenuList)
            })
          }
        }).catch((e) => {
          console.log(e);
          resolve()
        })
      } else {
        resolve()
      }
    });
  },
  pinPromise(data) {

    var compare = function (obj1, obj2) {
      var val1 = obj1.sort;
      var val2 = obj2.sort;
      if (val1 < val2) {
        return -1;
      } else if (val1 > val2) {
        return 1;
      } else {
        return 0;
      }
    }
    if (data.ifMap) {
      let routers = [];
      for (var key in data.ifMap) {
        var menu = data.ifMap[key].menuInfo;
        var btns = data.ifMap[key].menuBtnList;
        // console.log(menu, "btns")
        var router = {
          sort: menu.sort,
          path: menu.url,
          menuId: menu.menuId,
          pid: menu.pid,
          meta: { btns: btns },
          name: menu.menuName,
          iconCls: menu.menuIcon, //图标样式class
          children: []
        };
        // console.log(router, "111")
        //{ path: '/nav1/table', component: Table, name: 'Table' }
        if (router.pid > 0) {
          // console.log(routers, 'routers')
          var prouter = routers.find(e => e.menuId == router.pid);
          // console.log(prouter, 'pro')
          if (prouter) {
            prouter.children.push(router)

          } else {
            var pmenu = this.menulist.find(e => e.menuId == router.pid);
            // console.log(this.menulist, '324234')
            if (pmenu) {
              var prouter = {
                sort: pmenu.sort,
                path: pmenu.url,
                menuId: pmenu.menuId,
                pid: pmenu.pid,
                meta: { btns: btns },
                redirect: pmenu.url,
                name: pmenu.menuName,
                iconCls: pmenu.menuIcon, //图标样式class
                children: [router]
              };
              routers.push(prouter)
            }
          }
        } else {
          routers.push(router)
          // console.log(routers, '2222')
        }
      }
      routers.forEach(e => {
        e.children = e.children.sort(compare)
      })
      // console.log(routers.sort(compare))
      return routers.sort(compare)
    }
    return []
  }
}
export default permission